<?php
//收藏管理
class FavModel {
	
	/**
	 * 添加收藏
	 * @param array $data 参数数组( array('title'=>'标题', 'type'=>'fav', 'idid'=>'表中的id', 'table'=>'数据表', 'image'=>'图片') )
	 * @return boolean
	 */
	public function addFav($data=''){
		//uid
		$data['uid'] = My::user('userid');
		if(!My::is_id($data['uid'])) return false;
		//adddate
		$data['adddate'] = date("Y-m-d H:i:s");
		//type
		if(empty($data['type']))	return false;
		//idid
		if(!My::is_id($data['idid'])) return false;
		//table
		//$data['table']= $data['table'];
		//title
		if(empty($data['title']))	return false;
		//image
		//$data['image']= $data['image'];
		//cat_id
		$data['cat_id'] = isset($data['cat_id'])?(int)$data['cat_id']:0;
		//保存
		if(DB('fav')->where("uid={$data['uid']} AND idid='{$data['idid']}' AND `type`='{$data['type']}' AND cat_id='{$data['cat_id']}'")->count()==0){
			if($ok=DB('fav')->add($data))
				return $ok;
			else
				return false;
		}else
			return false;//已经存在
	}

	/**
	 * 取消收藏图片
	 * @param int $id 取消收藏的数据id
	 * @return boolean
	 */
	public function cancelFav($id=0){
		if(!My::is_id($id)) return false;
		$userid = My::user('userid');
		if(!My::is_id($userid)) return false;
		if($ok=DB('fav')->where("`id`={$id} AND `uid`={$userid}")->delete())
			return $ok;
		else
			return false;
	}


	/**
	 * 添加顶/踩(喜欢/一般)(1/0)
	 * @param array $data 参数数组(array('title'=>'标题', 'type'=>'fav', 'idid'=>'表中的id', 'table'=>'数据表', 'image'=>'图片') )
	 * @return array
	 */
	public function addLike($data=''){
		//adddate
		$data['adddate'] = date("Y-m-d H:i:s");
		//type
		if(empty($data['type']))  return 'fielderror';
		//idid
		if(!My::is_id($data['idid'])) return 'fielderror';
		//table
		if(empty($data['table'])) return 'fielderror';
		//title
		if(empty($data['title']))	return 'fielderror';
		//image 可选参数
		//$data['image']= $data['image'];
		//cat_id 可选参数
		$data['cat_id'] = isset($data['cat_id'])?(int)$data['cat_id']:0;
		//IP
		$data['ip'] = get_client_ip();
		//保存
		if(DB('fav')->where("ip='{$data['ip']}' AND idid='{$data['idid']}' AND `type`='{$data['type']}' AND `table`='{$data['table']}'")->count()==0){
			if($ok=DB('fav')->clear()->add($data)){
				//返回
				return json_encode(DB('fav')->field("count(id) as count, sum(`value`) as sum")->where("idid='{$data['idid']}' AND `type`='{$data['type']}' AND `table`='{$data['table']}'")->find());
			}else
				return 'dberror';
		}else
			return 'exists';//已经存在
	}
  
   
}